import { MessageSendInput } from "../dto/message.dto";
import { publish } from "./mqtt.service";
import { HttpError } from "../utils/httpError";
import { ErrorCode } from "../constants/errorCode";
import { PrismaClient } from "@prisma/client";
import * as attachmentService from "./attachments.service";
import * as conversationService from './conversation.service';
import { bigintToString } from "../utils/response";
const prisma = new PrismaClient();
export const sendGroupMessage = async (groupId: number, msg: any) => {
  await publish(`im/group/${groupId}`, msg);
};

export const sendPrivateMessage = async (
  uid1: number,
  uid2: number,
  msg: any
) => {
  const [a, b] = [uid1, uid2].sort((x, y) => x - y);
  const topic = `im/simple/${a}_${b}`;
  await publish(topic, msg);
};

// 导出一个异步函数sendNoticeMessage，用于发送通知消息
export const sendNoticeMessage = async (uid: number, msg: any) => {
  // 使用await关键字等待publish函数执行，将`im/notice/${uid}`和msg作为参数传入
  await publish(`im/notice/${uid}`, msg);
};

export const sendMessage = async (input: MessageSendInput) => {
  
  const { sender_id, receiver_id, group_id, type, content } = input;
  // ✅ 发送前：确保会话存在
  if (receiver_id) {
    // 私聊（双方）
    await conversationService.createOrUpdateConversation({
      user_id: sender_id,
      target_id: receiver_id,
      type: 1,
      last_message: content
    });

    await conversationService.createOrUpdateConversation({
      user_id: receiver_id,
      target_id: sender_id,
      type: 1,
      last_message: content
    });
  } else if (group_id) {
    // 群聊（仅自己）
    await conversationService.createOrUpdateConversation({
      user_id: sender_id,
      target_id: group_id,
      type: 2,
      last_message: content
    });
  }

  const message = await prisma.messages.create({
    data: {
      conversation_id: input.conversation_id,
      sender_id,
      receiver_id,
      group_id,
      type,
      content,
      has_attachment: input.has_attachment ?? 0
    }
  });



  if (input.has_attachment && input.attachment) {
    await attachmentService.saveAttachment({
      message_id: Number(message.id),
      url: input.attachment.url,
      type: input.attachment.type,
      name: input.attachment.name,
      size: input.attachment.size,
      mime: input.attachment.mime,
    });
  }
  
  return bigintToString(message);
};

export const recallMessage = async (messageId: number, userId: number) => {
  const message = await prisma.messages.findUnique({
    where: { id: messageId },
  });
  if (!message || Number(message.sender_id) !== userId) {
    throw new HttpError(ErrorCode.FORBIDDEN, 403, "无权限撤回");
  }

  return prisma.messages.update({
    where: { id: messageId },
    data: {
      is_recalled: 1,
      content: "", // 可清空原内容
      status: 2,
    },
  });
};

export const getMessages = async (
  conversation_id: number,
  limit = 20,
  cursor?: number
) => {
  const messages = await prisma.messages.findMany({
    where: { conversation_id },
    orderBy: { created_at: "desc" },
    take: limit,
    skip: cursor ? 1 : 0,
    cursor: cursor ? { id: cursor } : undefined,
  });

  return messages.reverse(); // 从旧到新
};
